﻿// controller to handle the image upload
angular.module('app.user').controller('UserImageUploadController', [
    '$scope', 'libraryMediator', '$state', 'notify',
    function ($scope, libraryMediator, $state, notify) {
		// register the controller with the mediator
    	libraryMediator.setUploadController(this);

    	$scope.model.uploadFiles = [];
		// function to handle the upload of one or more images
    	$scope.uploadFile = function () {
			// get the files to be uploaded
    		var files = $scope.model.uploadFiles;
			// require at least one image
    		if (files.length < 1) {
    			notify.warning('Please select an image to upload');
    			return;
    		}
			// notify that upload is in progress
			notify.info('Uploading...');
			// append the selected files to the form data
    		var fd = new FormData();
    		for (var ii = 0; ii < files.length; ++ii) {
    			fd.append("file", files[ii]);
    		}
			// add the current folder as the destination folder
    		fd.append("folder", $scope.getFolderId());
			// submit the upload
    		libraryMediator.upload(fd);
    	};
		// handle the image uploaded response
    	this.handleImageUploaded = function (data) {
    		$scope.model.uploadFiles = '';
			// if failed, return
    		if (data.length < 1) {
    			return;
    		}
			// if successful, notify success, otherwise notify the error
    		if (data[0].Successful) {
    			notify.success(data.length.toString() + ' image' + (data.length == 1 ? '' : 's') + ' uploaded.');
    		}
    		else { 
    			notify.error(data[0].Message);
    		}
    	}
    }]);